<template>
  <div class="expense-form-page">
    <van-nav-bar
      title="报销申请"
      left-arrow
      @click-left="onBackClick"
      fixed
    />
    <div class="content-area">
      <van-form @submit="onSubmit" class="expense-form">
        <!-- 基本信息 -->
        <van-cell-group inset title="基本信息">
          <!-- 报销类型 -->
          <van-field
            readonly
            clickable
            name="expenseType"
            :model-value="selectedExpenseType ? selectedExpenseType.name : ''"
            label="报销类型"
            placeholder="请选择报销类型"
            :rules="[{ required: true, message: '请选择报销类型' }]"
            @click="showExpenseTypePicker = true"
          />
          
          <!-- 部门信息 -->
          <van-field
            readonly
            clickable
            name="department"
            :model-value="formData.department"
            label="所属部门"
            placeholder="请选择部门"
            :rules="[{ required: true, message: '请选择部门' }]"
            @click="showDepartmentPicker = true"
          />
          
          <!-- 预算科目 -->
          <van-field
            readonly
            clickable
            name="budgetAccount"
            :model-value="formData.budgetAccount"
            label="预算科目"
            placeholder="请选择预算科目"
            :rules="[{ required: true, message: '请选择预算科目' }]"
            @click="showBudgetAccountPicker = true"
          />
          
          <!-- 报销事由 -->
          <van-field
            v-model="formData.reason"
            label="报销事由"
            type="textarea"
            placeholder="请输入报销事由"
            rows="2"
            autosize
            :rules="[{ required: true, message: '请填写报销事由' }]"
          />
          
          <!-- 关联项目 -->
          <van-field
            readonly
            clickable
            name="project"
            :model-value="formData.project"
            label="关联项目"
            placeholder="请选择关联项目(可选)"
            @click="showProjectPicker = true"
          />
          
          <!-- 报销总额 -->
          <van-field
            v-model="totalExpense"
            label="报销总额"
            type="number"
            readonly
            right-icon="info-o"
            @click-right-icon="showTip('报销总额将根据各项费用明细自动计算')"
          />
        </van-cell-group>
        
        <!-- 费用明细 -->
        <van-cell-group inset title="费用明细">
          <div class="expense-items">
            <van-empty v-if="expenseItems.length === 0" description="暂无费用明细" />
            <div v-else class="expense-item-list">
              <div v-for="(item, index) in expenseItems" :key="index" class="expense-item">
                <div class="expense-item-header">
                  <div class="expense-item-title">
                    {{ item.name }}
                    <van-tag type="primary" size="mini" v-if="item.source === 'invoice'" style="margin-left: 5px;">发票</van-tag>
                    <van-tag type="success" size="mini" v-else style="margin-left: 5px;">手动</van-tag>
                  </div>
                  <div class="expense-actions">
                    <van-icon name="edit" @click="editExpenseItem(index)" />
                    <van-icon name="cross" @click="removeExpenseItem(index)" />
                  </div>
                </div>
                <div class="expense-item-content">
                  <div class="expense-item-amount">¥{{ formatAmount(item.amount) }}</div>
                  <div class="expense-item-date">{{ item.date }}</div>
                  <div class="expense-item-desc" v-if="item.description">{{ item.description }}</div>
                </div>
              </div>
            </div>
            <div class="expense-tips" v-if="expenseItems.length > 0" style="margin-bottom: 10px; font-size: 13px; color: #969799;">
              <van-icon name="info-o" style="margin-right: 4px;"/> 提示：系统支持手动添加和从发票库生成两种方式创建费用明细
            </div>
            <div class="add-expense-btn">
              <van-button type="primary" size="small" icon="plus" plain @click="showAddExpenseDialog">
                手动添加明细
              </van-button>
            </div>
          </div>
        </van-cell-group>
        
        <!-- 票据附件 -->
        <van-cell-group inset title="票据附件">
          <div class="invoice-selector">
            <van-button type="primary" size="small" plain icon="search" @click="showInvoiceSelector = true">从发票库选择</van-button>
            <div class="invoice-tips">已选择 {{ selectedInvoices.length }} 张发票，可自动生成费用明细</div>
            <div class="selected-invoices" v-if="selectedInvoices.length > 0">
              <div class="invoice-tag" v-for="invoice in selectedInvoices" :key="invoice.id">
                <van-tag closeable @close="removeSelectedInvoice(invoice.id)">
                  {{ invoice.title }} (¥{{ formatAmount(invoice.amount) }})
                </van-tag>
              </div>
            </div>
          </div>
          <div class="uploader-container">
            <div class="uploader-title">其他附件（如有）</div>
            <van-uploader
              v-model="uploadedFiles"
              :max-count="9"
              :max-size="5 * 1024 * 1024"
              :before-read="beforeRead"
              :after-read="afterRead"
              @delete="deleteFile"
              multiple
            />
            <div class="upload-tips">
              请上传发票、收据等报销凭证，最多9个文件，每个文件不超过5MB
            </div>
          </div>
        </van-cell-group>
        
        <!-- 报销标准提示 -->
        <div class="expense-standards">
          <van-collapse v-model="activeCollapse">
            <van-collapse-item title="报销标准说明" name="1">
              <div class="standards-content">
                <p>1. 差旅费：符合医院差旅费管理办法规定的标准</p>
                <p>2. 会议费：单次不超过预算的20%，且不超过10000元</p>
                <p>3. 办公用品：单次不超过5000元</p>
                <p>4. 培训费：需提供培训证明，单次不超过预算的15%</p>
                <p>5. 医疗耗材：需提供使用记录和科室负责人签字</p>
                <p>6. 其他费用：需详细说明用途，单次不超过3000元</p>
              </div>
            </van-collapse-item>
          </van-collapse>
        </div>
        
        <!-- 审批流程展示 -->
        <van-cell-group inset title="审批流程">
          <div class="approval-flow">
            <van-steps direction="vertical" :active="0">
              <van-step>
                <template #default>
                  <div class="step-content">
                    <div class="step-title">提交申请</div>
                    <div class="step-desc">{{ currentUserName }}</div>
                  </div>
                </template>
              </van-step>
              <van-step>
                <template #default>
                  <div class="step-content">
                    <div class="step-title">部门主管审批</div>
                    <div class="step-desc">{{ departmentManagerName }}</div>
                  </div>
                </template>
              </van-step>
              <van-step>
                <template #default>
                  <div class="step-content">
                    <div class="step-title">财务审核</div>
                    <div class="step-desc">财务部</div>
                  </div>
                </template>
              </van-step>
              <van-step v-if="isBigExpense">
                <template #default>
                  <div class="step-content">
                    <div class="step-title">分管领导审批</div>
                    <div class="step-desc">院领导</div>
                  </div>
                </template>
              </van-step>
              <van-step>
                <template #default>
                  <div class="step-content">
                    <div class="step-title">财务支付</div>
                    <div class="step-desc">财务部</div>
                  </div>
                </template>
              </van-step>
            </van-steps>
          </div>
        </van-cell-group>
        
        <!-- 提交按钮 -->
        <div class="submit-buttons">
          <van-button round block type="primary" native-type="submit">
            提交报销
          </van-button>
          <van-button round block plain @click="saveDraft">
            保存草稿
          </van-button>
        </div>
      </van-form>
      
      <!-- 报销类型选择弹窗 -->
      <van-popup v-model:show="showExpenseTypePicker" position="bottom" round>
        <div class="popup-header">
          <div class="popup-title">选择报销类型</div>
          <van-icon name="cross" @click="showExpenseTypePicker = false" />
        </div>
        <van-radio-group v-model="selectedExpenseTypeId">
          <van-cell-group>
            <van-cell 
              v-for="type in expenseTypes" 
              :key="type.id" 
              :title="type.name" 
              clickable 
              @click="selectedExpenseTypeId = type.id"
            >
              <template #right-icon>
                <van-radio :name="type.id" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
        <div class="popup-footer">
          <van-button type="primary" block round @click="confirmExpenseType">确认选择</van-button>
        </div>
      </van-popup>
      
      <!-- 部门选择弹窗 -->
      <van-popup v-model:show="showDepartmentPicker" position="bottom" round>
        <div class="popup-header">
          <div class="popup-title">选择部门</div>
          <van-icon name="cross" @click="showDepartmentPicker = false" />
        </div>
        <van-picker
          show-toolbar
          :columns="departmentOptions"
          @confirm="onDepartmentConfirm"
          @cancel="showDepartmentPicker = false"
        />
      </van-popup>
      
      <!-- 预算科目选择弹窗 -->
      <van-popup v-model:show="showBudgetAccountPicker" position="bottom" round>
        <div class="popup-header">
          <div class="popup-title">选择预算科目</div>
          <van-icon name="cross" @click="showBudgetAccountPicker = false" />
        </div>
        <van-picker
          show-toolbar
          :columns="budgetAccountOptions"
          @confirm="onBudgetAccountConfirm"
          @cancel="showBudgetAccountPicker = false"
        />
      </van-popup>
      
      <!-- 项目选择弹窗 -->
      <van-popup v-model:show="showProjectPicker" position="bottom" round>
        <div class="popup-header">
          <div class="popup-title">选择关联项目</div>
          <van-icon name="cross" @click="showProjectPicker = false" />
        </div>
        <van-picker
          show-toolbar
          :columns="projectOptions"
          @confirm="onProjectConfirm"
          @cancel="showProjectPicker = false"
        />
      </van-popup>
      
      <!-- 添加费用明细弹窗 -->
      <CustomPopup
        v-model:show="showExpenseDialog"
        :title="isEditingExpense ? '编辑费用明细' : '添加费用明细'"
        @close="handleExpenseDialogClose"
      >
        <div class="expense-dialog-content">
          <div>
            <van-cell-group inset>
              <van-field
                v-model="currentExpense.name"
                label="费用名称"
                placeholder="请输入费用名称"
                :rules="[{ required: true, message: '请输入费用名称' }]"
              />
              <van-field
                v-model="currentExpense.amount"
                type="number"
                label="金额"
                placeholder="请输入金额"
                :rules="[{ required: true, message: '请输入金额' }]"
              >
                <template #right-icon>
                  <span class="amount-unit">元</span>
                </template>
              </van-field>
              <van-field
                v-model="currentExpense.date"
                readonly
                clickable
                label="日期"
                placeholder="请选择日期"
                @click="showDatePicker = true"
                :rules="[{ required: true, message: '请选择日期' }]"
              />
              <van-field
                v-model="currentExpense.description"
                type="textarea"
                label="说明"
                placeholder="请输入费用说明"
                rows="3"
                autosize
              />
            </van-cell-group>
          </div>
        </div>
        
        <template #footer>
          <div class="popup-footer-buttons">
            <van-button plain type="default" @click="cancelExpense">取消</van-button>
            <van-button type="primary" @click="confirmExpense">保存</van-button>
          </div>
        </template>
      </CustomPopup>
      
      <!-- 日期选择器 -->
      <van-popup v-model:show="showDatePicker" position="bottom" round>
        <van-datetime-picker
          title="选择日期"
          type="date"
          :min-date="new Date(new Date().getFullYear() - 1, 0, 1)"
          :max-date="new Date()"
          @confirm="onDateConfirm"
          @cancel="showDatePicker = false"
        />
      </van-popup>
      
      <!-- 发票选择弹窗 -->
      <van-popup v-model:show="showInvoiceSelector" position="bottom" round>
        <div class="popup-header">
          <div class="popup-title">选择关联发票</div>
          <van-icon name="cross" @click="showInvoiceSelector = false" />
        </div>
        <div class="invoice-filter">
          <van-search v-model="invoiceSearchText" placeholder="搜索发票" />
          <div class="filter-actions">
            <van-dropdown-menu>
              <van-dropdown-item v-model="invoiceFilterStatus" :options="invoiceStatusOptions" />
            </van-dropdown-menu>
            <van-checkbox v-model="selectAll" @click="toggleSelectAll">全选</van-checkbox>
          </div>
        </div>
        <div class="invoice-list">
          <van-checkbox-group v-model="selectedInvoiceIds">
            <van-cell 
              v-for="invoice in filteredInvoices" 
              :key="invoice.id" 
            >
              <template #icon>
                <div class="invoice-checkbox-wrapper" @click.stop="toggleInvoiceSelection(invoice.id)">
                  <van-checkbox :name="invoice.id" />
                </div>
              </template>
              <template #title>
                <div class="invoice-content" @click="toggleInvoiceSelection(invoice.id)">
                  <div class="invoice-title">{{ invoice.title }}</div>
                  <div class="invoice-label">发票代码: {{ invoice.code }} · {{ invoice.date }}</div>
                </div>
              </template>
              <template #right-icon>
                <div class="invoice-amount">¥{{ formatAmount(invoice.amount) }}</div>
              </template>
            </van-cell>
          </van-checkbox-group>
          <van-empty v-if="filteredInvoices.length === 0" description="未找到符合条件的发票" />
        </div>
        <div class="invoice-selection-summary" v-if="selectedInvoiceIds.length > 0">
          <div class="summary-content">
            已选择 <span class="highlight">{{ selectedInvoiceIds.length }}</span> 张发票，
            金额合计 <span class="highlight">¥{{ formatAmount(totalSelectedAmount) }}</span>
          </div>
        </div>
        <div class="popup-footer">
          <van-button type="primary" block round @click="confirmInvoiceSelection">确认选择({{ selectedInvoiceIds.length }})</van-button>
        </div>
      </van-popup>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Form, Field, CellGroup, Cell, Button, Uploader, Popup, RadioGroup, Radio, 
  Icon, Toast, Search, DropdownMenu, DropdownItem, Checkbox, CheckboxGroup, 
  Empty, Tag, Collapse, CollapseItem, Steps, Step, DatetimePicker, Dialog, Picker,
  NavBar
} from 'vant'
import CustomPopup from '@/components/CustomPopup.vue'
import 'vant/es/toast/style'
import 'vant/es/dialog/style'

export default {
  name: 'ExpenseForm',
  components: {
    vanForm: Form,
    vanField: Field,
    vanCellGroup: CellGroup,
    vanCell: Cell,
    vanButton: Button,
    vanUploader: Uploader,
    vanPopup: Popup,
    vanRadioGroup: RadioGroup,
    vanRadio: Radio,
    vanIcon: Icon,
    vanSearch: Search,
    vanDropdownMenu: DropdownMenu,
    vanDropdownItem: DropdownItem,
    vanCheckbox: Checkbox,
    vanCheckboxGroup: CheckboxGroup,
    vanEmpty: Empty,
    vanTag: Tag,
    vanCollapse: Collapse,
    vanCollapseItem: CollapseItem,
    vanSteps: Steps,
    vanStep: Step,
    vanDatetimePicker: DatetimePicker,
    vanDialog: Dialog,
    vanPicker: Picker,
    vanNavBar: NavBar,
    CustomPopup
  },
  setup() {
    const router = useRouter()
    
    // 当前用户信息（实际项目中应从用户状态获取）
    const currentUserName = '张医生'
    const departmentManagerName = '李主任'
    
    // 确保所有弹窗状态显式初始化为false，防止自动弹出
    const showExpenseDialog = ref(false)
    const showDatePicker = ref(false)
    const showInvoiceSelector = ref(false)
    const showExpenseTypePicker = ref(false)
    const showDepartmentPicker = ref(false)
    const showBudgetAccountPicker = ref(false)
    const showProjectPicker = ref(false)
    // 标记用户是否主动打开对话框
    const userTriggeredDialog = ref(false)

    // 页面挂载时确保所有弹窗都关闭
    onMounted(() => {
      // 立即重置所有弹窗状态
      resetAllDialogs()
      
      // 确保DOM更新后再次检查并强制关闭所有对话框
      setTimeout(() => {
        // 只有在非用户触发的情况下才关闭对话框
        if (!userTriggeredDialog.value) {
          resetAllDialogs()
        }
      }, 100)
    })

    // 在组件销毁前清理
    onBeforeUnmount(() => {
      // 确保所有弹窗都关闭，避免内存泄漏
      resetAllDialogs()
    })

    // 重置所有弹窗状态的函数
    const resetAllDialogs = () => {
      // 只有在非用户触发的情况下才重置对话框状态
      if (!userTriggeredDialog.value) {
        console.log('重置所有对话框状态')
        showExpenseDialog.value = false
        showDatePicker.value = false
        showInvoiceSelector.value = false
        showExpenseTypePicker.value = false
        showDepartmentPicker.value = false
        showBudgetAccountPicker.value = false
        showProjectPicker.value = false
      }
    }
    
    // 返回上一页
    const onBackClick = () => {
      router.back()
    }
    
    // 折叠面板激活项
    const activeCollapse = ref([])
    
    // 表单数据
    const formData = reactive({
      expenseTypeId: null,
      department: '',
      budgetAccount: '',
      reason: '',
      project: '',
      attachments: [],
      invoices: [] // 存储关联的发票ID
    })
    
    // 费用明细项
    const expenseItems = ref([])
    
    // 大额报销标志（超过5000元需要院领导审批）
    const isBigExpense = computed(() => {
      let total = 0;
      if (expenseItems.value && expenseItems.value.length > 0) {
        total = expenseItems.value.reduce((sum, item) => {
          return sum + (parseFloat(item.amount) || 0);
        }, 0);
      }
      return total >= 5000;
    })
    
    // 附件上传相关
    const uploadedFiles = ref([])
    
    // 报销类型相关
    const selectedExpenseTypeId = ref(null)
    const expenseTypes = [
      { id: 1, name: '差旅费报销' },
      { id: 2, name: '办公用品报销' },
      { id: 3, name: '会议费报销' },
      { id: 4, name: '培训费报销' },
      { id: 5, name: '医疗耗材报销' },
      { id: 6, name: '其他费用报销' }
    ]
    
    // 获取选中的报销类型
    const selectedExpenseType = computed(() => {
      if (!selectedExpenseTypeId.value) return null
      return expenseTypes.find(item => item.id === selectedExpenseTypeId.value)
    })
    
    // 确认报销类型选择
    const confirmExpenseType = () => {
      if (!selectedExpenseTypeId.value) {
        Toast('请选择一个报销类型')
        return
      }
      formData.expenseTypeId = selectedExpenseTypeId.value
      showExpenseTypePicker.value = false
    }
    
    // 部门选择相关
    const departmentOptions = [
      '内科', '外科', '妇产科', '儿科', '急诊科', 
      '放射科', '检验科', '药剂科', '医务科', '护理部', '行政部'
    ]
    
    // 确认部门选择
    const onDepartmentConfirm = (value) => {
      formData.department = value
      showDepartmentPicker.value = false
    }
    
    // 预算科目选择相关
    const budgetAccountOptions = [
      '医疗支出', '科研经费', '教学经费', '基本建设费', 
      '行政费用', '设备采购', '人员培训', '其他支出'
    ]
    
    // 确认预算科目选择
    const onBudgetAccountConfirm = (value) => {
      formData.budgetAccount = value
      showBudgetAccountPicker.value = false
    }
    
    // 项目选择相关
    const projectOptions = [
      '无关联项目', '新冠防控项目', '医院信息化建设', '人才培养计划', 
      '设备更新项目', '科研项目A', '科研项目B', '健康宣教项目'
    ]
    
    // 确认项目选择
    const onProjectConfirm = (value) => {
      formData.project = value === '无关联项目' ? '' : value
      showProjectPicker.value = false
    }
    
    // 添加费用明细相关
    const isEditingExpense = ref(false)
    const editingExpenseIndex = ref(-1)
    const currentExpense = reactive({
      name: '',
      amount: '',
      date: '',
      description: ''
    })
    
    // 显示添加费用明细对话框
    const showAddExpenseDialog = () => {
      try {
        // 标记用户触发
        userTriggeredDialog.value = true
        
        // 重置表单数据
        isEditingExpense.value = false
        currentExpense.name = ''
        currentExpense.amount = ''
        currentExpense.date = formatDate(new Date()) // 默认为当天日期
        currentExpense.description = ''
        
        // 使用延时确保状态更新后再打开对话框
        setTimeout(() => {
          showExpenseDialog.value = true
          console.log('主动打开费用明细对话框', showExpenseDialog.value)
        }, 50)
      } catch (error) {
        console.error('打开费用明细对话框出错:', error)
        Toast('操作失败，请重试')
      }
    }
    
    // 编辑费用明细
    const editExpenseItem = (index) => {
      try {
        // 标记用户触发
        userTriggeredDialog.value = true
        
        isEditingExpense.value = true
        editingExpenseIndex.value = index
        const item = expenseItems.value[index]
        currentExpense.name = item.name
        currentExpense.amount = item.amount
        currentExpense.date = item.date
        currentExpense.description = item.description
        
        // 使用延时确保状态更新后再打开对话框
        setTimeout(() => {
          showExpenseDialog.value = true
          console.log('主动打开编辑费用明细对话框', showExpenseDialog.value)
        }, 50)
      } catch (error) {
        console.error('编辑费用明细出错:', error)
        Toast('操作失败，请重试')
      }
    }
    
    // 移除费用明细
    const removeExpenseItem = (index) => {
      // 使用一个独立的confirm对话框，不要触发表单验证
      Dialog.confirm({
        title: '确认删除',
        message: '确定要删除该费用明细吗？',
        beforeClose: (action, done) => {
          if (action === 'confirm') {
            expenseItems.value.splice(index, 1)
            Toast('删除成功')
          }
          done();
        }
      });
    }
    
    // 日期选择确认
    const onDateConfirm = (date) => {
      currentExpense.date = formatDate(date)
      showDatePicker.value = false
    }
    
    // 确认保存费用明细
    const confirmExpense = () => {
      console.log('保存费用明细', currentExpense);
      
      // 验证表单
      if (!currentExpense.name) {
        Toast('请输入费用名称')
        return
      }
      if (!currentExpense.amount || isNaN(parseFloat(currentExpense.amount))) {
        Toast('请输入有效金额')
        return
      }
      if (!currentExpense.date) {
        Toast('请选择日期')
        return
      }
      
      try {
        // 创建新的费用明细对象
        const expenseItem = {
          name: currentExpense.name,
          amount: parseFloat(currentExpense.amount || 0),
          date: currentExpense.date,
          description: currentExpense.description,
          // 记录来源：手动添加
          source: 'manual'
        }
        
        console.log('准备保存的费用明细:', expenseItem);
        
        if (isEditingExpense.value && editingExpenseIndex.value >= 0) {
          // 编辑模式 - 保留原来的source
          const originalSource = expenseItems.value[editingExpenseIndex.value].source || 'manual';
          expenseItem.source = originalSource;
          // 保留发票关联信息（如果有）
          if (expenseItems.value[editingExpenseIndex.value].invoiceId) {
            expenseItem.invoiceId = expenseItems.value[editingExpenseIndex.value].invoiceId;
          }
          console.log('更新费用明细，索引:', editingExpenseIndex.value);
          expenseItems.value[editingExpenseIndex.value] = expenseItem;
        } else {
          // 新增模式
          console.log('添加新费用明细');
          expenseItems.value.push(expenseItem);
        }
        
        console.log('当前费用明细列表:', expenseItems.value);
        
        // 清空表单数据并关闭弹窗
        showExpenseDialog.value = false;
        // 重置用户触发标记
        userTriggeredDialog.value = false;
        
        // 显示成功提示
        Toast.success('费用明细保存成功');
      } catch (error) {
        console.error('添加费用明细时出错:', error);
        Toast.fail('操作失败，请重试');
      }
    }
    
    // 取消添加/编辑费用明细
    const cancelExpense = () => {
      showExpenseDialog.value = false
      userTriggeredDialog.value = false
    }
    
    // 处理对话框关闭后的清理
    const handleExpenseDialogClose = () => {
      userTriggeredDialog.value = false;
      // 询问用户是否保存更改
      if (isFormDirty()) {
        Dialog.confirm({
          title: '确认关闭',
          message: '是否放弃未保存的更改？',
        }).then(() => {
          // 用户确认放弃
          resetExpenseForm();
        }).catch(() => {
          // 用户取消，重新打开弹窗
          nextTick(() => {
            showExpenseDialog.value = true;
          });
        });
      } else {
        // 如果表单没有修改，直接关闭
        resetExpenseForm();
      }
    };
    
    // 检查表单是否有变动
    const isFormDirty = () => {
      return currentExpense.name || 
             currentExpense.amount || 
             currentExpense.date || 
             currentExpense.description;
    };
    
    // 重置费用表单
    const resetExpenseForm = () => {
      currentExpense.name = '';
      currentExpense.amount = '';
      currentExpense.date = '';
      currentExpense.description = '';
    };
    
    // 计算报销总额
    const totalExpense = computed(() => {
      let total = 0
      if (expenseItems.value && expenseItems.value.length > 0) {
        expenseItems.value.forEach(item => {
          if (item && item.amount) {
            total += parseFloat(item.amount) || 0
          }
        })
      }
      return total.toFixed(2)
    })
    
    // 格式化日期
    const formatDate = (date) => {
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    // 格式化金额显示
    const formatAmount = (amount) => {
      if (!amount || isNaN(parseFloat(amount))) return '0.00'
      return parseFloat(amount).toLocaleString('zh-CN', { 
        minimumFractionDigits: 2, 
        maximumFractionDigits: 2 
      })
    }
    
    // 发票选择相关
    const invoiceSearchText = ref('')
    const invoiceFilterStatus = ref('all')
    const selectedInvoiceIds = ref([])
    const selectedInvoices = ref([])
    const selectAll = ref(false)
    
    const invoiceStatusOptions = [
      { text: '全部发票', value: 'all' },
      { text: '已验证', value: 'verified' },
      { text: '待使用', value: 'unused' }
    ]
    
    // 模拟发票数据
    const availableInvoices = ref([
      {
        id: 1,
        title: '某航空公司',
        code: '044001900311',
        date: '2023-10-15',
        type: 'electronic',
        status: 'verified',
        amount: 1580.00,
        imageUrl: 'https://example.com/invoice1.jpg'
      },
      {
        id: 2,
        title: '某餐饮有限公司',
        code: '044001900312',
        date: '2023-10-12',
        type: 'electronic',
        status: 'verified',
        amount: 328.50,
        imageUrl: 'https://example.com/invoice2.jpg'
      },
      {
        id: 3,
        title: '某酒店有限公司',
        code: '044001900313',
        date: '2023-10-10',
        type: 'vat-normal',
        status: 'verified',
        amount: 1260.00,
        imageUrl: 'https://example.com/invoice3.jpg'
      },
      {
        id: 4,
        title: '高铁票',
        code: '044001900314',
        date: '2023-10-08',
        type: 'electronic',
        status: 'verified',
        amount: 620.00,
        imageUrl: 'https://example.com/invoice4.jpg'
      },
      {
        id: 5,
        title: '医疗器械有限公司',
        code: '044001900315',
        date: '2023-10-12',
        type: 'vat-special',
        status: 'verified',
        amount: 3760.50,
        imageUrl: 'https://example.com/invoice5.jpg'
      },
      {
        id: 6,
        title: '某科技有限公司',
        code: '044001900316',
        date: '2023-10-11',
        type: 'vat-special',
        status: 'verified',
        amount: 450.00,
        imageUrl: 'https://example.com/invoice6.jpg'
      }
    ])
    
    // 根据筛选条件过滤发票
    const filteredInvoices = computed(() => {
      if (!availableInvoices.value) return []
      
      let result = [...availableInvoices.value]
      
      // 根据状态筛选
      if (invoiceFilterStatus.value !== 'all') {
        result = result.filter(invoice => invoice.status === invoiceFilterStatus.value)
      }
      
      // 根据搜索文本筛选
      if (invoiceSearchText.value) {
        const searchText = invoiceSearchText.value.toLowerCase()
        result = result.filter(invoice => 
          invoice.title.toLowerCase().includes(searchText) || 
          invoice.code.includes(searchText)
        )
      }
      
      return result
    })
    
    // 计算已选发票总金额
    const totalSelectedAmount = computed(() => {
      if (!selectedInvoiceIds.value || selectedInvoiceIds.value.length === 0) return 0
      if (!availableInvoices.value) return 0
      
      return availableInvoices.value
        .filter(invoice => selectedInvoiceIds.value.includes(invoice.id))
        .reduce((sum, invoice) => sum + (invoice.amount || 0), 0)
    })
    
    // 切换发票选择状态
    const toggleInvoiceSelection = (id) => {
      if (!id || !selectedInvoiceIds.value) return
      
      // 查找ID在数组中的位置
      const index = selectedInvoiceIds.value.indexOf(id)
      
      // 如果ID不在数组中，添加它；否则，从数组中移除它
      if (index === -1) {
        selectedInvoiceIds.value.push(id)
      } else {
        selectedInvoiceIds.value.splice(index, 1)
      }
      
      // 检查是否应该更新全选状态
      if (filteredInvoices.value && filteredInvoices.value.length > 0) {
        selectAll.value = filteredInvoices.value.every(invoice => 
          selectedInvoiceIds.value.includes(invoice.id)
        )
      }
    }
    
    // 全选/取消全选发票
    const toggleSelectAll = () => {
      if (!filteredInvoices.value || !selectedInvoiceIds.value) return
      
      if (selectAll.value) {
        // 全选当前过滤后的发票
        selectedInvoiceIds.value = filteredInvoices.value.map(invoice => invoice.id)
      } else {
        // 取消全选
        selectedInvoiceIds.value = []
      }
    }
    
    // 确认发票选择
    const confirmInvoiceSelection = () => {
      if (!availableInvoices.value || !selectedInvoiceIds.value) return
      
      try {
        // 根据选中的ID更新选中的发票列表
        selectedInvoices.value = availableInvoices.value.filter(
          invoice => selectedInvoiceIds.value.includes(invoice.id)
        )
        
        // 将选中的发票ID添加到表单数据
        formData.invoices = [...selectedInvoiceIds.value]
        
        showInvoiceSelector.value = false
        Toast(`已选择${selectedInvoices.value.length}张发票`)
        
        // 自动创建费用明细
        createExpenseItemsFromInvoices()
      } catch (error) {
        console.error('确认发票选择时出错:', error)
        Toast('操作失败，请重试')
      }
    }
    
    // 移除已选择的发票
    const removeSelectedInvoice = (id) => {
      if (!id || !selectedInvoices.value || !selectedInvoiceIds.value) return
      
      // 从选中列表中移除
      selectedInvoices.value = selectedInvoices.value.filter(invoice => invoice.id !== id)
      
      // 从选中ID中移除
      const index = selectedInvoiceIds.value.indexOf(id)
      if (index !== -1) {
        selectedInvoiceIds.value.splice(index, 1)
      }
      
      // 更新表单数据
      formData.invoices = [...selectedInvoiceIds.value]
    }
    
    // 根据选择的发票创建费用明细
    const createExpenseItemsFromInvoices = () => {
      if (!selectedInvoices.value || selectedInvoices.value.length === 0) return
      
      const newExpenseItems = []
      
      // 检查是否存在相同发票的费用明细
      const existingInvoiceIds = new Set(
        expenseItems.value
          .filter(item => item.invoiceId)
          .map(item => item.invoiceId)
      )
      
      // 为每张新发票创建费用明细
      selectedInvoices.value.forEach(invoice => {
        // 避免重复添加
        if (existingInvoiceIds.has(invoice.id)) return
        
        // 确定费用类型
        let expenseName = '其他费用'
        if (invoice.title.includes('航空') || invoice.title.includes('机票') || 
            invoice.title.includes('火车') || invoice.title.includes('出租') || 
            invoice.title.includes('交通')) {
          expenseName = '交通费'
        } 
        else if (invoice.title.includes('酒店') || invoice.title.includes('住宿') || 
                invoice.title.includes('宾馆')) {
          expenseName = '住宿费'
        } 
        else if (invoice.title.includes('餐') || invoice.title.includes('食') || 
                invoice.title.includes('饮')) {
          expenseName = '餐饮费'
        }
        else if (invoice.title.includes('医疗') || invoice.title.includes('器械') || 
                invoice.title.includes('药')) {
          expenseName = '医疗耗材'
        }
        
        newExpenseItems.push({
          name: expenseName,
          amount: invoice.amount,
          date: invoice.date,
          description: `发票号码：${invoice.code}，${invoice.title}`,
          invoiceId: invoice.id, // 记录关联的发票ID
          source: 'invoice' // 记录来源：发票生成
        })
      })
      
      // 添加新的费用明细
      expenseItems.value = [...expenseItems.value, ...newExpenseItems]
      
      if (newExpenseItems.length > 0) {
        Toast(`已根据发票自动创建${newExpenseItems.length}项费用明细`)
      }
    }
    
    // 监听过滤条件变化，更新全选状态
    watch([invoiceFilterStatus, invoiceSearchText], () => {
      // 如果过滤条件变化，检查当前是否全选
      if (filteredInvoices.value && filteredInvoices.value.length > 0) {
        selectAll.value = filteredInvoices.value.every(invoice => 
          selectedInvoiceIds.value.includes(invoice.id)
        )
      } else {
        selectAll.value = false
      }
    })
    
    // 添加watch监听器，确保对话框状态变化时不会意外打开
    watch(showExpenseDialog, (newVal) => {
      if (newVal && document.activeElement === null) {
        console.log('检测到对话框异常打开，强制关闭')
        showExpenseDialog.value = false
      }
    }, { immediate: true })
    
    // 文件上传前检查
    const beforeRead = (file) => {
      const isImage = file.type.indexOf('image') !== -1
      const isPDF = file.type === 'application/pdf'
      if (!isImage && !isPDF) {
        Toast('请上传图片或PDF格式文件')
        return false
      }
      return true
    }
    
    // 文件上传后处理
    const afterRead = (file) => {
      try {
        console.log('File uploaded:', file)
        // 实际项目中应该调用API上传文件到服务器
        // 模拟上传成功
        file.status = 'done'
        file.message = '上传成功'
        // 添加到表单数据
        formData.attachments.push({
          name: file.file.name,
          url: URL.createObjectURL(file.file),
          size: file.file.size
        })
      } catch (error) {
        console.error('文件上传处理出错:', error)
        Toast('文件处理失败，请重试')
      }
    }
    
    // 删除文件
    const deleteFile = (file) => {
      if (!file || !formData.attachments) return
      
      const index = formData.attachments.findIndex(item => item.url === file.url)
      if (index !== -1) {
        formData.attachments.splice(index, 1)
      }
    }
    
    // 提示信息
    const showTip = (message) => {
      Toast(message)
    }
    
    // 保存草稿
    const saveDraft = () => {
      if (!formData.expenseTypeId) {
        Toast('请选择报销类型')
        return
      }
      
      // 草稿保存逻辑
      Toast.success('草稿保存成功')
      console.log('保存草稿:', {
        ...formData,
        expenseItems: expenseItems.value,
        totalExpense: totalExpense.value
      })
    }
    
    // 提交表单
    const onSubmit = () => {
      if (!expenseItems.value || expenseItems.value.length === 0) {
        Toast('请添加至少一项费用明细')
        return
      }
      
      // 如果是大额报销，给出提示
      if (isBigExpense.value) {
        Dialog.confirm({
          title: '提示',
          message: '您的报销金额超过5000元，需要院领导审批，审批周期可能较长，是否继续提交？',
        }).then(() => {
          submitProcess()
        }).catch(() => {
          // 用户取消提交
        })
      } else {
        submitProcess()
      }
    }
    
    // 提交处理
    const submitProcess = () => {
      Toast.loading({
        message: '提交中...',
        forbidClick: true,
        duration: 2000
      })
      
      try {
        // 实际提交逻辑
        console.log('提交报销:', {
          ...formData,
          expenseItems: expenseItems.value,
          totalExpense: totalExpense.value
        })
        
        // 模拟提交成功
        setTimeout(() => {
          Toast.success('报销申请提交成功')
          setTimeout(() => router.back(), 1500)
        }, 2000)
      } catch (error) {
        console.error('提交报销申请时出错:', error)
        Toast.fail('提交失败，请重试')
      }
    }
    
    return {
      onBackClick,
      currentUserName,
      departmentManagerName,
      activeCollapse,
      formData,
      expenseItems,
      isBigExpense,
      uploadedFiles,
      totalExpense,
      expenseTypes,
      selectedExpenseTypeId,
      selectedExpenseType,
      showExpenseTypePicker,
      confirmExpenseType,
      showDepartmentPicker,
      departmentOptions,
      onDepartmentConfirm,
      showBudgetAccountPicker,
      budgetAccountOptions,
      onBudgetAccountConfirm,
      showProjectPicker,
      projectOptions,
      onProjectConfirm,
      showExpenseDialog,
      showDatePicker,
      currentExpense,
      showAddExpenseDialog,
      editExpenseItem,
      removeExpenseItem,
      onDateConfirm,
      handleExpenseDialogClose,
      showInvoiceSelector,
      invoiceSearchText,
      invoiceFilterStatus,
      selectedInvoiceIds,
      selectedInvoices,
      invoiceStatusOptions,
      filteredInvoices,
      toggleInvoiceSelection,
      toggleSelectAll,
      confirmInvoiceSelection,
      removeSelectedInvoice,
      totalSelectedAmount,
      selectAll,
      beforeRead,
      afterRead,
      deleteFile,
      showTip,
      formatAmount,
      saveDraft,
      onSubmit,
      resetAllDialogs,
      userTriggeredDialog,
      confirmExpense,
      cancelExpense,
      isFormDirty,
      resetExpenseForm
    }
  }
}
</script>

<style scoped>
.expense-form-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 80px;
  height: 100%;
  overflow-y: auto;
}

.content-area {
  padding: 16px;
  padding-top: 56px; /* Account for fixed navbar height */
  height: 100%;
  overflow-y: auto;
}

.expense-form {
  width: 100%;
  overflow-y: visible;
}

.submit-buttons {
  margin: 24px 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 费用明细样式 */
.expense-items {
  padding: 8px 0;
}

.expense-item-list {
  margin-bottom: 16px;
}

.expense-item {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.expense-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.expense-item-title {
  font-weight: 500;
  font-size: 15px;
  color: #323233;
}

.expense-actions {
  display: flex;
  gap: 16px;
}

.expense-actions .van-icon {
  color: #969799;
  font-size: 18px;
}

.expense-item-content {
  font-size: 14px;
  color: #646566;
  line-height: 1.5;
}

.expense-item-amount {
  color: #ee0a24;
  font-weight: 500;
  margin-bottom: 4px;
}

.expense-item-date {
  margin-bottom: 4px;
}

.expense-item-desc {
  font-size: 12px;
  color: #969799;
  line-height: 1.5;
}

.expense-tips {
  margin-bottom: 10px;
  font-size: 13px;
  color: #969799;
}

.add-expense-btn {
  display: flex;
  justify-content: center;
  margin-top: 8px;
}

/* 票据附件样式 */
.invoice-selector {
  margin-bottom: 16px;
}

.invoice-tips {
  margin: 8px 0;
  font-size: 14px;
  color: #969799;
}

.selected-invoices {
  display: flex;
  flex-wrap: wrap;
  margin-top: 8px;
}

.invoice-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.uploader-container {
  margin-top: 16px;
}

.uploader-title {
  margin-bottom: 8px;
  font-size: 14px;
  color: #323233;
}

.upload-tips {
  margin-top: 8px;
  color: #969799;
  font-size: 12px;
  line-height: 1.5;
}

/* 审批流程样式 */
.approval-flow {
  padding: 16px 0;
}

.step-content {
  padding: 0 8px;
}

.step-title {
  font-size: 14px;
  font-weight: 500;
  color: #323233;
}

.step-desc {
  font-size: 12px;
  color: #969799;
  margin-top: 4px;
}

/* 报销标准说明 */
.expense-standards {
  margin: 16px;
}

.standards-content {
  font-size: 13px;
  line-height: 1.5;
  color: #646566;
}

.standards-content p {
  margin: 8px 0;
}

/* 弹窗样式 */
.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
}

.popup-title {
  font-size: 16px;
  font-weight: 500;
}

.popup-footer {
  padding: 16px;
  border-top: 1px solid #ebedf0;
}

.expense-dialog-header {
  padding: 16px;
  text-align: center;
  border-bottom: 1px solid #ebedf0;
}

.expense-dialog-title {
  font-size: 18px;
  font-weight: 500;
  color: #323233;
}

.expense-dialog-content {
  padding: 16px 0;
  overflow-y: auto;
  max-height: calc(100% - 60px);
}

.amount-unit {
  color: #969799;
  font-size: 14px;
}

/* 发票选择样式 */
.invoice-filter {
  padding: 8px 16px;
  border-bottom: 1px solid #ebedf0;
}

.filter-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
  padding: 0 8px;
}

.filter-actions .van-checkbox {
  margin-left: 12px;
}

.invoice-list {
  max-height: 300px;
  overflow-y: auto;
}

.invoice-checkbox-wrapper {
  padding: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.invoice-content {
  display: flex;
  flex-direction: column;
  padding: 4px 0;
  cursor: pointer;
}

.invoice-title {
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 4px;
}

.invoice-label {
  color: #969799;
  font-size: 12px;
}

.invoice-amount {
  margin-right: 12px;
  font-weight: 500;
  color: #ff976a;
  font-size: 15px;
}

.invoice-selection-summary {
  background-color: #f7f8fa;
  padding: 12px 16px;
  border-top: 1px solid #ebedf0;
  font-size: 14px;
}

.summary-content {
  text-align: center;
}

.highlight {
  color: #1989fa;
  font-weight: 500;
}

/* 添加弹窗按钮样式 */
.popup-footer-buttons {
  display: flex;
  gap: 12px;
}

.popup-footer-buttons .van-button {
  flex: 1;
}
</style> 